from flask_restplus import Resource, Namespace, fields, marshal, reqparse, Model
from common.decorators import catch_error
from app.user.decorators import token_required
from common.responses import ok
from flask import g
from common.response_model import base_model, pagination_model
from common.request_parser import get_parser as base_get_parser
from app.product.attribute.model import Attribute
from app.product.attribute import dao

api = Namespace('attribute')

# ---------- model ----------
attribute_model = base_model.inherit('attribute_model', {
    'is_default': fields.Boolean(description='是否默认'),
})
attribute_paginate_model = pagination_model.inherit('attribute_paginate_model', {
    "items": fields.Nested(attribute_model)
})
# ---------- create parser ----------
create_parser = reqparse.RequestParser()
create_parser.add_argument('name', type=str, help='单位名称')
create_parser.add_argument('notes', type=str, help='备注')
create_parser.add_argument('is_default', type=bool, choices=[True, False], help='是否默认')
create_parser.add_argument('is_active', type=bool, choices=[True, False], help='是否启用')
create_parser.add_argument('specification_id', type=int)

# ---------- get parser ----------
get_parser = base_get_parser.copy()
get_parser.add_argument('specification_id', type=int)
get_parser.replace_argument('sorted_by', type=str, choices=[
    'name', 'id'
], default='id', help='sorted_by')


# create_parser.add_argument('num_of_base_attribute', type=float, help='单位换算关系')
# create_parser.add_argument('spu_id', type=int)


class AttributesResource(Resource):
    @catch_error
    @token_required
    @api.expect(create_parser)
    def post(self):
        args = create_parser.parse_args()
        new_obj = Attribute.create(**args, commit=True)
        return ok(data=marshal(new_obj, attribute_model),
                  message='create success')

    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        """获取列表"""
        args = get_parser.parse_args()
        pagination = dao.get_by_page(**args)
        return ok(data=marshal(pagination, attribute_paginate_model),
                  message='get success')


# ---------- put parser ----------
put_parser = create_parser.copy()
put_parser.remove_argument('specification_id')


class AttributeResource(Resource):
    @catch_error
    @token_required
    def get(self, obj_id):
        """获取"""
        obj = Attribute.query.filter_by(id=obj_id).first()
        # obj = service.get(g.user_id, obj_id)
        return ok(data=marshal(obj, attribute_model),
                  message='get success')

    @catch_error
    @token_required
    @api.expect(put_parser)
    def put(self, obj_id):
        """更新"""
        args = put_parser.parse_args()
        for key in list(args.keys()):
            if args.get(key) is None:
                del args[key]
        obj = Attribute.query.filter_by(id=obj_id).first()
        obj.update(**args, commit=True)
        # obj = service.update(g.user_id, obj_id, **args)
        return ok(data=marshal(obj, attribute_model),
                  message='update success')

    @catch_error
    @token_required
    def delete(self, obj_id):
        """删除"""
        obj = Attribute.query.filter_by(id=obj_id).first()
        delete_id = obj.hard_delete(commit=True)
        # delete_id = service.delete(g.user_id, obj_id)
        return ok(
            data={
                'id': delete_id
            },
            message='delete success')


api.add_resource(AttributesResource, '/attrs')
api.add_resource(AttributeResource, '/attrs/<int:obj_id>')

# 注册 response 文档
api.models[attribute_model.name] = attribute_model
